<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header-section">
      <uni-icons type="back" size="30" @click="goBack"></uni-icons>
      <view class="title">商品详情</view>
      <!-- <uni-icons type="search" size="30" @click="goSearch"></uni-icons> -->
    </view>

    <!-- 商品图片轮播 -->
    <view class="">
      <swiper autoplay interval="1800" circular class="swiper-container">
        <swiper-item v-for="(image, index) in productImages" :key="index">
          <image :src="baseUrl + image.imageUrl" class="product-image" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
    </view>

    <!-- 商品信息 -->
    <view class="product-info">
      <text class="product-name">{{ product.productName }}</text>
      <view class="product-price-stock">
        <text class="product-price">¥{{ product.productPrice }}</text>
      </view>
      <text class="product-description">{{ product.productDescription }}</text>
      <text class="product-type">类型：{{ product.productType }}</text>
      <text class="store-id">商店ID：{{ product.storeId }}</text>
    </view>

    <!-- 商品评论区 -->
    <view class="comments-section">
      <text class="comments-title">评论区</text>
      <view v-for="(comment, index) in productComments" :key="index" class="comment-item">
        <image :src="baseUrl + comment.user_logo" class="comment-avatar"></image>
        <view class="comment-content">
          <text class="comment-username">{{ comment.user_name }}</text>
          <view class="comment-rating">
            <uni-icons v-for="n in 5" :key="n" type="star" size="20"
              :color="n <= comment.user_rating ? '#FFD700' : '#CCCCCC'"></uni-icons>
          </view>
          <text class="comment-text">{{ comment.user_comment }}</text>
        </view>
      </view>
    </view>

    <!-- 规格信息 -->
    <view class="specifications">
      <view class="spec-buttons">
        <button v-for="(spec, index) in productSpecifications" :key="index" class="spec-item"
          :class="{ 'uni-active': selectedSpecIndex === index }" @click="onSpecSelected(index)">
          {{ spec.specName }}: {{ spec.specValue }}
        </button>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="footer">
      <view class="operation-buttons">
        <view class="theButton" @click="goToShopPage(product.storeId)">
          <view class="iconfont icon-dianpu text-black icon"></view>
          <text class="text">店铺</text>
        </view>
        <view class="theButton">
          <view class="iconfont icon-kefu text-black icon"></view>
          <text class="text">客服</text>
        </view>
      </view>
      <view class="action-buttons">
        <button class="add-to-cart" @click="showSpecSelection('cart')">加入购物车</button>
        <button class="buy-now" @click="showSpecSelection('buy')">立即购买</button>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <uni-popup ref="specSelectionPopup" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view class="popup-title">规格选择</view>
        <view class="spec-buttons">
          <view v-for="(spec, index) in availableSpecifications" :key="index" class="spec-item-container">
            <button class="spec-item-popup" :class="{ 'uni-active': selectedSpecIndex === index }"
              @click="onSpecSelected(index, spec)">
              {{ spec.specName }}
              <view>￥{{ spec.specValue }}</view>
            </button>
          </view>
        </view>
        <view class="quantity-selector">
          <text>数量：</text>
          <input type="number" v-model="selectedQuantity" class="quantity-input" @input="quantityChange" />
        </view>
        <view class="spec-value">￥{{ this.item.itemUnit }}</view>
        <view class="actions">
          <button class="cancel" @click="closePopup">取消</button>
          <button class="confirm" @click="onConfirm">确定</button>
        </view>
      </view>
    </uni-popup>
	
  </view>
</template>

<script>
  import { getProductDetail, getProductSpecifications } from '@/api/login.js';
  import { AddItemToCart , getProductComments} from '../../../api/cart';
  import { getShopById } from '../../../api/shop';
  import config from '@/config';
  const baseUrl = config.baseUrl;

  export default {
    data() {
      return {
        baseUrl: '',
        productId: '',
        product: {},
        productComments: [], // 评论数据
        productImages: [],
        productSpecifications: [],
        availableSpecifications: [], // 后端返回的规格数据
        selectedSpecIndex: -1, // 用户选择的规格索引
        selectedQuantity: 1, // 用于存储选中的数量
        actionType: '', // 操作类型，'cart' 表示加入购物车，'buy' 表示立即购买
        item: {
          cartId: '',
          userId: '',
          productId: '',
          specName: '',
          specValue: '',
          productCnt: '',
          itemUnit: '',
          itemStatus: '',
        }
      };
    },
    methods: {
      goBack() {
        uni.navigateBack();
      },
      goSearch() {
        uni.navigateTo({
          url: '/pages/search/search'
        });
      },
      fetchProductDetail(productId) {
        getProductDetail(productId).then(response => {
          if (response.code === 200) {
            const data = response.data;
            this.product = data;
            this.productImages = data.productImages || [];
            this.productSpecifications = data.productSpecifications || [];
            this.productComments = data.productComments || []; // 确保正确赋值
          }
        }).catch(error => {
          console.error(error);
        });
      },
      fetchProductComments(productId) {
        getProductComments(productId).then(response => {
          if (response.code === 200) {
            const data = response.data;
            this.productComments = data;
			console.log(this.productComments);
          }
        }).catch(error => {
          console.error(error);
        });
      },
      // 显示规格选择弹窗
      showSpecSelection(type) {
        this.actionType = type;
        this.fetchProductSpecifications(this.productId);
      },
      fetchProductSpecifications(productId) {
        getProductSpecifications(productId).then(response => {
          if (response.code === 200) {
            this.availableSpecifications = response.data;
            this.$refs.specSelectionPopup.open();
          } else {
            console.error(response.message);
          }
        }).catch(error => {
          console.error(error);
        });
      },
      // 确认选择规格后的回调
      onSpecSelected(index, spec) {
        this.selectedSpecIndex = index;
        this.item.specName = spec.specName;
        this.item.specValue = spec.specValue;
        this.item.productId = this.product.productId;
        this.item.itemUnit = this.item.specValue * this.item.productCnt;
      },
      quantityChange(e) {
        this.selectedQuantity = e.detail.value;
        this.item.productCnt = e.detail.value;
        this.item.itemUnit = this.item.specValue * this.item.productCnt;
      },
      onConfirm() {
        if (this.selectedSpecIndex !== -1) {
          const spec = this.availableSpecifications[this.selectedSpecIndex];
          if (this.actionType === 'cart') {
            this.addToCart(spec);
          } else if (this.actionType === 'buy') {
            this.buyNow(spec);
			uni.showToast({
				title:"操作成功",
				duration:2000
			})
          }
          this.$refs.specSelectionPopup.close();
        } else {
          console.error('Please select a specification.');
        }
      },
      addToCart(spec) {
        this.item.itemStatus = "有效";
        AddItemToCart(this.item).then(res => {
          console.log(res);
        })
      },
      buyNow(spec) {
        console.log(this.item);
      },
      closePopup() {
        this.$refs.specSelectionPopup.close();
      },
      // 跳转到商店页面
      goToShopPage(storeId) {
        uni.navigateTo({
          url: `/pages/service/shopDetail?storeId=${storeId}`
        });
      },
    },
    onLoad(options) {
      if (options.productId) {
        this.productId = options.productId;
        this.fetchProductDetail(this.productId);
        this.fetchProductComments(this.productId);
        this.item.productCnt = this.selectedQuantity;
      }
      this.baseUrl = baseUrl;
      this.$store.dispatch('GetInfo').then(res => {
        this.item.userId = res.appUser.userId;
        this.item.cartId = res.appUser.userId;
      })
    },
  };
</script>

<style scoped>
  .container {
    background-color: #f5f5f5;
    padding-bottom: 60px;
  }

  .header-section {
    display: flex;
    align-items: center;
    padding: 10px;
    background-color: #ffffff;
    position: fixed;
    top: 0;
    width: 100%;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 10;
  }

  .title {
    font-size: 18px;
    font-weight: bold;
  }

  .swiper-container {
    width: 100%;
    height: 400px;
    margin-top: 20px;
  }

  .product-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .product-info {
    margin-top: 10px;
    padding: 15px;
    background-color: #ffffff;
  }

  .product-name {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .product-price-stock {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .product-price {
    font-size: 18px;
    color: #ff4d4f;
  }

  .product-stock {
    font-size: 16px;
    color: #666;
  }

  .product-description,
  .product-type,
  .store-id {
    font-size: 16px;
    color: #666;
    margin-bottom: 10px;
    display: block;
  }

  .specifications {
    margin-top: 10px;
    padding: 15px;
    background-color: #ffffff;
  }

  .spec-buttons {
    display: flex;
    flex-wrap: wrap;
  }

  .spec-value {
    font-size: 18px;
    color: #ff5500;
    font-weight: bold;
    margin-top: 5px;
    text-align: right;
  }

  .spec-item {
    display: block;
    margin-right: 10px;
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    background-color: #f5f5f5;
    cursor: pointer;
  }

  .spec-item.uni-active {
    background-color: #007AFF;
    color: #ffffff;
    border-color: #007AFF;
  }

  .footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #ffffff;
    position: fixed;
    bottom: 0;
    width: 100%;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  }

  .operation-buttons {
    display: flex;
    align-items: center;
  }

  .theButton {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 15px;
  }

  .icon {
    font-size: 24px;
  }

  .text {
    font-size: 14px;
  }

  .action-buttons {
    display: flex;
  }

  .add-to-cart,
  .buy-now {
    margin: 0 5px;
    padding: 15px 20px;
    border-radius: 30px;
    font-size: 16px;
    color: #ffffff;
    text-align: center;
	
  }

  .add-to-cart {
    background-color: #ff9800;
  }

  .buy-now {
    background-color: #ff4d4f;
  }

  /* 弹窗样式 */
  .popup-content {
    background-color: #ffffff;
    padding: 15px;
  }

  .popup-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .actions {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
  }

  .actions button {
    padding: 10px 20px;
    border-radius: 5px;
    font-size: 16px;
    cursor: pointer;
  }

  .cancel {
    background-color: #999;
    color: #ffffff;
  }

  .confirm {
    background-color: #007AFF;
    color: #ffffff;
  }

  .spec-item-popup {
    display: flex;
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    background-color: #f5f5f5;
    cursor: pointer;
  }

  .spec-item-popup.uni-active {
    background-color: #007AFF;
    color: #ffffff;
    border-color: #007AFF;
  }

  .quantity-selector {
    display: flex;
    align-items: center;
    margin-top: 20px;
  }

  .quantity-input {
    margin-left: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 5px;
    font-size: 16px;
    min-height: 30px;
  }
  
   .comments-section {
       margin-top: 20px;
       padding: 15px;
       background-color: #ffffff;
     }
   
     .comments-title {
       font-size: 20px;
       font-weight: bold;
       margin-bottom: 15px;
     }
   
     .comment-item {
       display: flex;
       align-items: flex-start;
       margin-bottom: 15px;
     }
   
     .comment-avatar {
       width: 40px;
       height: 40px;
       border-radius: 20px;
       margin-right: 10px;
     }
   
     .comment-content {
       flex: 1;
	   margin-top: 20px;
     }
   
     .comment-header {
       display: flex;
       justify-content: space-between;
       align-items: center;
       margin-bottom: 5px;
     }
   
     .comment-username {
       font-size: 16px;
       font-weight: bold;
     }
   
     .comment-rating {
       display: flex;
     }
   
     .comment-rating uni-icons {
       margin-right: 3px;
     }
   
     .comment-text {
       font-size: 14px;
     }
</style>
